<template>
  <a-card :bordered="false">
    <div class="card-title">{{ $route.meta.title }}</div>
    <div class="table-operator">
      <!-- 搜索板块 -->
      <a-row class="row-item-search">
        <a-form class="search-form" :form="searchForm" layout="inline" @submit="handleSearch">
          <a-form-item label="门店名称">
            <a-input v-decorator="['storeName']" placeholder="请输入门店名称" />
          </a-form-item>
          <a-form-item label="状态">
            <a-select placeholder="请选择状态" v-model="queryParam.state">
              <a-select-option :value="-1">全部</a-select-option>
              <a-select-option :value="0">待领取</a-select-option>
              <a-select-option :value="1">申请中</a-select-option>
              <a-select-option :value="2">已发放</a-select-option>
              <a-select-option :value="3">拒绝</a-select-option>
            </a-select>
          </a-form-item>
          <a-form-item class="search-btn">
            <a-button type="primary" icon="search" html-type="submit">搜索</a-button>
            <a-button style="margin-left: 20px;" type="danger" @click="exportExcel">导出</a-button>
          </a-form-item>
        </a-form>
      </a-row>
    </div>
    <s-table
      :row-selection="rowSelection"
      ref="table"
      rowKey="id"
      :loading="isLoading"
      :columns="columns"
      :data="loadData"
      :pageSize="15"
    >
      <span slot="account" slot-scope="_, item">
        <div>
          <p>{{ item.bank }}</p>
          <p>{{ item.rname }}</p>
          <p>{{ item.account }}</p>
        </div>
      </span>
      <span slot="time" slot-scope="_, item">
        <div>
          <p v-if="item.apply_at > 0">申请：{{ item.apply_at * 1000 | at }}</p>
          <p v-if="item.apply_at == 0">申请：-</p>
          <p v-if="item.take_at > 0">发放：{{ item.take_at * 1000 | at }}</p>
          <p v-if="item.take_at == 0">发放：-</p>
        </div>
      </span>
      <span slot="certificate" slot-scope="text">
        <div class="avatar">
          <img v-if="text" width="45" height="45" :src="host + '/uploads/' + text" alt="用户头像" />
          <img v-else width="45" height="45" src="~@/assets/img/default-avatar.png" alt="用户头像" />
        </div>
      </span>
      <span slot="certificate" slot-scope="text">
        <a title="点击查看原图" :href="host + '/uploads/' + text" target="_blank">
          <img v-if="text" width="45" height="45" :src="host + '/uploads/' + text" alt="用户头像" />
          <img v-else width="45" height="45" src="~@/assets/img/default-avatar.png" alt="用户头像" />
        </a>
      </span>
      <!-- 操作 -->
      <span class="actions" slot="action" slot-scope="item">
        <a v-if="item.state == 2 && !item.certificate" title="上传凭证" @click="handleUpload(item)">上传凭证</a>
        <a v-if="item.state == 1" title="发放" @click="handleTake(item)">发放</a>
        <a v-if="item.state == 1" title="拒绝" @click="handleCancle(item)">拒绝</a>
      </span>
    </s-table>
    <Upload ref="uploadModal" @handleSubmit="handleRefresh" />
  </a-card>
</template>

<script>
import * as Api from '@/api/user'
import { STable } from '@/components'
import Upload from './Upload'
import moment from 'moment'
import ExportJsonExcel from 'js-export-excel'

export default {
  name: 'Index',
  components: {
    STable,
    Upload
  },
  data () {
    return {
      host: window.serverConfig.DOMAIN,
      rowSelection: {},
      selections: [],
      searchForm: this.$form.createForm(this),
      // 查询参数
      queryParam: {},
      // 正在加载
      isLoading: false,
      // 表头
      columns: [
        {
          title: '商家名称',
          dataIndex: 'store_name'
        },
        {
          title: '当前余额',
          dataIndex: 'balance'
        },
        {
          title: '状态',
          dataIndex: 'state',
          customRender: (value) => {
            let response = ''
            switch (value) {
              case 0:
                response = '待领取'
                break

              case 1:
                response = '申请中'
                break

              case 2:
                response = '已发放'
                break

              case 3:
                response = '拒绝'
                break
            }
            return response
          }
        },
        {
          title: '发放金额',
          dataIndex: 'money'
        },
        // {
        //   title: '触发时间',
        //   dataIndex: 'create_at',
        //   customRender: (value) => {
        //     if (!value) return '-'
        //     return moment(value * 1000).format('LLLL')
        //   }
        // },
        {
          title: '节点',
          dataIndex: 'apply_at',
          scopedSlots: { customRender: 'time' }
        },
        {
          title: '凭证',
          dataIndex: 'certificate',
          scopedSlots: { customRender: 'certificate' }
        },
        {
          title: '账户',
          dataIndex: 'account',
          scopedSlots: { customRender: 'account' }
        },
        {
          title: '操作',
          // dataIndex: 'action',
          width: '180px',
          scopedSlots: { customRender: 'action' }
        }
      ],
      // 加载数据方法 必须为 Promise 对象
      loadData: param => {
        return Api.clist({ ...param, ...this.queryParam })
          .then(response => {
            return response.data.list
          })
      }
    }
  },
  created () {
    this.rowSelection = {
      onChange: (selectedRowKeys, selectedRows) => {
        this.selections = selectedRows
        // console.log(`selectedRowKeys: ${selectedRowKeys}`, 'selectedRows: ', selectedRows)
      },
      onSelect: (record, selected, selectedRows) => {
        // this.selections.push(record)
        // console.log(record, selected, selectedRows)
      },
      onSelectAll: (selected, selectedRows, changeRows) => {
        if (selected) {
          this.selections = selectedRows
        } else {
          this.selections = []
        }
      }
    }
  },
  methods: {

    exportExcel () {
      const data = this.selections// 选中的数据
      const dataTable = []
      if (data && data.length > 0) {
        for (const i in data) {
          if (data[i]) {
            // eslint-disable-next-line no-unused-vars
            let response = ''
            switch (data[i].state) {
              case 0:
                response = '待领取'
                break

              case 1:
                response = '申请中'
                break

              case 2:
                response = '已发放'
                break

              default:
                response = '拒绝'
                break
            }
            const obj = {
              '商家名称': data[i].store_name,
              '商家余额': data[i].balance,
              '发放状态': response,
              '领取金额': data[i].money,
              '触发时间': moment(data[i].create_at * 1000).format('LLLL'),
              '申请时间': moment(data[i].apply_at * 1000).format('LLLL'),
              '发放时间': moment(data[i].take_at * 1000).format('LLLL'),
              '银行': data[i].bank,
              '姓名': data[i].rname,
              '开户行': data[i].account
            }
            dataTable.push(obj)
          }
        }
        this.exportToExcel(dataTable)
      }
    },
    exportToExcel (dataTable) {
      const option = {}
      option.fileName = '发放记录'
      option.datas = [
        {
          sheetData: dataTable,
          sheetName: '抚恤金发放记录',
          sheetFilter: [
            '商家名称',
            '商家余额',
            '发放状态',
            '领取金额',
            '触发时间',
            '申请时间',
            '发放时间',
            '银行',
            '姓名',
            '开户行'
          ],
          sheetHeader: [
            '商家名称',
            '商家余额',
            '发放状态',
            '领取金额',
            '触发时间',
            '申请时间',
            '发放时间',
            '银行',
            '姓名',
            '开户行'
          ]
        }
      ]
      const toExcel = new ExportJsonExcel(option)
      toExcel.saveExcel()
    },

    handleTake (item) {
      const that = this
      this.$confirm({
        title: '确认提示',
        content: `确认发放？`,
        okType: 'danger',
        onOk () {
          Api.take({ id: item.id })
            .then(response => {
              that.$message.success(response.message)
              that.handleRefresh(true)
            })
        }
      })
    },

    handleUpload (item) {
      this.$refs.uploadModal.add(item)
    },

    handleCancle (item) {
      const that = this
      this.$confirm({
        title: '确认提示',
        content: `确认确认？`,
        okType: 'danger',
        onOk () {
          Api.cancle({ id: item.id })
            .then(response => {
              that.$message.success(response.message)
              that.handleRefresh(true)
            })
        }
      })
    },

    // 确认搜索
    handleSearch (e) {
      e.preventDefault()
      this.searchForm.validateFields((error, values) => {
        if (!error) {
          this.queryParam = { ...this.queryParam, ...values }
          this.handleRefresh(true)
        }
      })
    },

    /**
     * 刷新列表
     * @param Boolean bool 强制刷新到第一页
     */
    handleRefresh (bool = false) {
      this.$refs.table.refresh(bool)
    }

  }
}
</script>

<style lang="less" scoped>
.ant-card-body {
  padding: 22px 29px 25px;
}

.platform {
  .icon {
    font-size: 17px;
  }

  .MP-WEIXIN {
    color: #04be02;
  }

  .H5 {
    color: #e44c27;
  }
}
</style>
